from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware
import time
import sys
from . import config

ENABLE_DBG = 0
RST_EXIT_MODE = 0
DBG_LST = []


def load_dbg_mode():  # 加载调试模式
    global ENABLE_DBG, observer, event_handler
    ENABLE_DBG = 1


def watch_plug(plugpath):  # 监听单个插件
    global ENABLE_DBG
    if (ENABLE_DBG):
        DBG_LST.append(plugpath)


def add_timer(app: FastAPI):  # 请求计时
    class RequestTimerMiddleware(BaseHTTPMiddleware):
        async def dispatch(self, request: Request, call_next):
            start_time = time.time()  # 计时
            response = await call_next(request)
            process_time = time.time() - start_time
            # 单位换算
            # 浏览器计时提示
            response.headers["Server-Timing"] = f"app;dur={int(process_time * 1000)}"
            if (process_time*1000*1000 < 1):
                process_str = f"{round(process_time*1000*1000*1000)}ns"
            elif (process_time*1000 < 1):
                process_str = f"{round(process_time*1000*1000)}μs"
            elif (process_time*1000 < 1000):
                process_str = f"{round(process_time*1000)}ms"
            else:
                process_str = f"{round(process_time)}s"
            sys.stderr.write(
                f"==> {process_str:>5} {'['+request.method+']':>7}{request.url.path}\n")
            return response
    app.add_middleware(RequestTimerMiddleware)  # 注册中间件
